package com.gmrz.uaf.servlet.v1.handler;

import com.gmrz.uaf.common.GuiceUtil;
import com.gmrz.uaf.protocol.v1.json.UAFSchemaBuilder;
import com.gmrz.uaf.remote.plugin.UASServiceProvider;
import com.gmrz.uaf.server.ServerContext;
import com.gmrz.uaf.servlet.v1.response.ExtendRespPayload;
import com.gmrz.uas.plugin.exception.PluginException;
import com.gmrz.uas.plugin.provider.ServiceProvider;
import com.gmrz.uas.plugin.uasextend.RestExtendPlugin;


/**
 * Created by gongyuqiang on 2017/5/25.
 */
public class UAFExtendHandler {

    protected  final static String EXTEND_PLUGIN_CLASSNAME = "com.gmrz.uas.plugin.uasextend.UASRestExtend";

    public String handlePost(String request){
        String response = null;
        ExtendRespPayload respPayload = new ExtendRespPayload();
        try {
            ServerContext.getServerContext().getFidoLog().setRequest(request);
            Class clz = Class.forName(EXTEND_PLUGIN_CLASSNAME);
            RestExtendPlugin plugin= (RestExtendPlugin) GuiceUtil.getProcessorInjector().getInstance(clz);
            ServiceProvider provider = GuiceUtil.getProcessorInjector().getInstance(UASServiceProvider.class);
            plugin.setServiceProvider(provider);
            String pluginResp = plugin.processPost(request);

            respPayload.setStatusCode(1200);
            respPayload.setDescription("OK");
            respPayload.setUafResponse(pluginResp);

        }
        catch (ClassNotFoundException e){
            respPayload.setStatusCode(1500);
            respPayload.setDescription("not found extend implement");
        }
        catch (PluginException e){
            respPayload.setStatusCode(1500);
            respPayload.setDescription("Failed to process extend request." + e.getErrorMsg());
        }
        catch(Exception e){
            respPayload.setStatusCode(1500);
            respPayload.setDescription("Failed to process extend request." + e.getMessage());
        }
        return UAFSchemaBuilder.getGson().toJson(respPayload);
    }
}
